/*
 * my_lib.c
 *
 *  Created on: Nov 26, 2012
 *      Author: andrey
 */

#include "main.h"
#include "my_lib.h"
#include "rficonsole.h"


#ifndef CHIBIOS
static __IO uint32_t CurrentTime = 0;

// this method is invoked by system tick interrupt
void TimingDelay_Decrement(void) {
	CurrentTime++;
}

int GetCurrentTime() {
	return CurrentTime;
}

void Delay(__IO uint32_t msDelay) {
	// save number of needed ticks
	int expectedTimingDelay = CurrentTime + 1 * msDelay;
	// wait for the ticks to happen (see TimingDelay_Decrement)
	while (CurrentTime < expectedTimingDelay)
		;
}
#endif

uint32_t getRCC_AHB1Periph(GPIO_TypeDef* GPIOx) {
	if (GPIOx == GPIOA )
		return RCC_AHB1Periph_GPIOA ;
	if (GPIOx == GPIOB )
		return RCC_AHB1Periph_GPIOB ;
	if (GPIOx == GPIOC )
		return RCC_AHB1Periph_GPIOC ;
	if (GPIOx == GPIOD )
		return RCC_AHB1Periph_GPIOD ;
	if (GPIOx == GPIOE )
		return RCC_AHB1Periph_GPIOE ;
	fatal("getRCC_AHB1Periph");
	return -1;
}

void enablePortClock(GPIO_TypeDef* GPIOx) {
	/* Enable the GPIOx Clock */
	RCC_AHB1PeriphClockCmd(getRCC_AHB1Periph(GPIOx), ENABLE);
}

void mySTM_EVAL_LEDInit(uint32_t pin, GPIO_TypeDef* GPIOx) {
	GPIO_InitTypeDef GPIO_InitStructure;

	enablePortClock(GPIOx);

	/* Configure the GPIO_LED pin */
	GPIO_InitStructure.GPIO_Pin = pin;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOx, &GPIO_InitStructure);
}

void turnPinOff(GPIO_TypeDef* GPIOx, uint32_t pinBits) {
	GPIOx->BSRRH = pinBits;
}

void turnPinOn(GPIO_TypeDef* GPIOx, uint32_t pinBits) {
	GPIOx->BSRRL = pinBits;
}

char *portname(GPIO_TypeDef* GPIOx) {
	if (GPIOx == GPIOA )
		return "PA";
	if (GPIOx == GPIOB )
		return "PB";
	if (GPIOx == GPIOC )
		return "PC";
	if (GPIOx == GPIOD )
		return "PD";
	if (GPIOx == GPIOE )
		return "PE";
	if (GPIOx == GPIOF )
		return "PF";
	return "unknown";
}

void Timing10ms() {
	// this is needed for FatFS

}
